package com.simple.mq.sdk.register;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.simple.mq.common.entity.RegisterQueueInfo;
import com.simple.mq.sdk.client.SimpleMQClient;
import com.simple.mq.sdk.producer.SimpleMqProducer;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;
import java.util.*;

/**
 * 项目: simple-mq
 * <p>
 * 功能描述:
 *
 * @author: WuChengXing
 * @create: 2023-09-16 23:26
 **/
@Slf4j(topic = "SimpleRegister")
public class SimpleRegister {

    private static String url = "ws://localhost:18888/";

    private static final List<SimpleMqProducer> list = new ArrayList<>(1);

    public void registerQueues(SimpleMqInitQueuesService simpleMqInitQueuesService) {
        registerQueues(simpleMqInitQueuesService.initQueues());
    }

    public static void init(RegisterConnectInfo registerConnectInfo) {
        if (Objects.nonNull(registerConnectInfo) && Objects.nonNull(registerConnectInfo.getPort()) && StrUtil.isNotEmpty(registerConnectInfo.getHost())) {
            url = "ws://" + registerConnectInfo.getHost() + ":" + registerConnectInfo.getPort() + "/";
        }
        log.info("connect address：【{}】", url);
    }

    public static void registerQueues(List<RegisterQueueInfo> registerQueueInfos) {
        SimpleMqProducer simpleMqProducer = null;
        if (list.isEmpty()) {
            simpleMqProducer = new SimpleMqProducer(URI.create(url), "Register Producer");
            list.add(simpleMqProducer);
        } else {
            simpleMqProducer = list.get(0);
        }
        simpleMqProducer.send(registerQueueInfos, "default.register");
    }

    public void remove() {
        if (list.isEmpty()) {
            return;
        }
        SimpleMqProducer simpleMqProducer = list.get(0);
        if (Objects.nonNull(simpleMqProducer)) {
            SimpleMQClient client = simpleMqProducer.getClient();
            client.close();
        }
        list.remove(0);
    }
}
